﻿using ACC.Data.Entities.Client;
using ACC.Data.Entities.Common;
using ACC.Data.Entities.Mes;
using ACC.Extensions.Entities;
using ACC.Extensions.Utilities;
using System;
using System.Collections.Generic;

namespace ACC.Extensions.ClientBusiness
{
    public class AccSocketServer
    {
        private object _lockObj = new object();
        private SocketServer _socketServer;
        private int _port;
        public bool IsAccConnected { get; set; } //标志ACC是否连接

        public AccSocketServer(int inPort)
        {
            _port = inPort;
            if (_port == 0)
            {
                _port = 9999;
            }
            try
            {
                _socketServer = new SocketServer(_port);
                _socketServer.OnReceiveRequest += ReceiveRequest;
                _socketServer.Start();
                _socketServer.OnConnected += _socketServer_OnConnected;
                _socketServer.OnDisconnected += _socketServer_OnDisconnected;
                IsAccConnected = _socketServer.IsConnected;
            }
            catch (Exception ex)
            {
                Log4Helper.Error("Start scoket error: ", ex);
                _socketServer.Stop();
                throw ex;
            }
        }

        private void _socketServer_OnConnected()
        {
            IsAccConnected = true;
            if (OnAccConnected != null)
            {
                OnAccConnected();
            }
        }

        private void _socketServer_OnDisconnected()
        {
            IsAccConnected = false;
            if (OnAccDisconnected != null)
            {
                OnAccDisconnected();
            }
        }
        public bool GetAccSocketStatus()
        {
            IsAccConnected = _socketServer.IsConnected;
            return _socketServer.IsConnected;
        }
        public void AccSocketStop()
        {
            IsAccConnected = false;
            if (OnAccDisconnected != null)
            {
                OnAccDisconnected();
            }
            //_socketServer.Stop();
        }
        private void ReceiveRequest(ACCServerRequest cmd)
        {
            if (string.IsNullOrEmpty(cmd.Parameters.ToString()))
            {
                return;
            }
            lock (_lockObj)
            {
                switch (cmd.ServerCmd)
                {
                    case ACCCmd.ClientConfig:
                        //首次连接上，需要初始化Client的配置对象
                        UISession.CurrentClient = JsonHelper.ToObject<ClientConfig>(cmd.Parameters.ToString());
                        Log4Helper.Info(cmd.Parameters.ToString());
                        if (UISession.CurrentClient != null)
                        {
                            //_hasGotConfig = true;
                            if (OnClientConfigChanged != null)
                            {
                                OnClientConfigChanged();
                            }
                        }
                        break;
                    case ACCCmd.ClientLogin:
                        //有员工登陆，（可能是线长在其他工位进行指派的）
                        ClientOperator oper = JsonHelper.ToObject<ClientOperator>(cmd.Parameters.ToString());
                        if (oper != null)
                        {
                            if (OnOperatorChanged != null)
                            {
                                OnOperatorChanged(oper);
                            }
                        }
                        break;

                    case ACCCmd.ClientModelChange:
                        ClientPartType partType =
                            JsonHelper.ToObject<ClientPartType>(cmd.Parameters.ToString());
                        if (partType != null && OnChangeover != null)
                        {
                            OnChangeover(partType);
                        }
                        break;
                    case ACCCmd.ClientComponentSet:
                        //  物料批次扫料后变化通知
                        List<ClientLotTrackItem> lots = JsonHelper.ToObject<List<ClientLotTrackItem>>(cmd.Parameters.ToString());
                        if (lots != null && OnLotTrackChanged != null) OnLotTrackChanged(lots);
                        break;
                    case ACCCmd.ClientShift:
                        ClientShiftCfg csc = JsonHelper.ToObject<ClientShiftCfg>(cmd.Parameters.ToString());
                        if (csc != null && OnShiftChanged != null) OnShiftChanged(csc);
                        break;
                    case ACCCmd.ClientUserDefined1:
                        // Working Instruction 工艺文件、操作指导 
                        List<MESWI> wis = JsonHelper.ToObject<List<MESWI>>(cmd.Parameters.ToString());
                        if (wis != null && OnWISChanged != null) OnWISChanged(wis);
                        break;
                    case ACCCmd.ClientUserDefined2:
                        // QC issue 售后、质量问题 
                        List<MESIssue> issues = JsonHelper.ToObject<List<MESIssue>>(cmd.Parameters.ToString());
                        if (issues != null && OnIssueChanged != null) OnIssueChanged(issues);
                        break;
                    case ACCCmd.ClientUserDefined3:
                        // MES GB码下发
                        MESSerialNumberSync gbsnData = JsonHelper.ToObject<MESSerialNumberSync>(cmd.Parameters.ToString());
                        if (gbsnData != null && !string.IsNullOrEmpty(gbsnData.gb_sn) && OnReceivedGBSN != null) OnReceivedGBSN(gbsnData.gb_sn);
                        break;
                }
            }
        }


        //ACC连接事件
        public delegate void AccConnectedHandler();
        public event AccConnectedHandler OnAccConnected;

        //ACC断开事件
        public delegate void AccDisconnectedHandler();
        public event AccDisconnectedHandler OnAccDisconnected;

        //ACC换型通知
        public delegate void ChangeoverHandler(ClientPartType partType);
        public event ChangeoverHandler OnChangeover;

        //获取到Client信息的事件
        public delegate void ClientConfigChangedHandler();
        public event ClientConfigChangedHandler OnClientConfigChanged;

        //操作工更换事件
        public delegate void OperatorChangedHandler(ClientOperator oper);
        public event OperatorChangedHandler OnOperatorChanged;

        //填充物料信息
        public delegate void LotTrackChangedHandler(List<ClientLotTrackItem> lots);
        public event LotTrackChangedHandler OnLotTrackChanged;

        //填充工艺文件
        public delegate void WISChangedHandler(List<MESWI> wis);
        public event WISChangedHandler OnWISChanged;

        //填充售后，质量问题
        public delegate void IssueChangedHandler(List<MESIssue> issues);
        public event IssueChangedHandler OnIssueChanged;

        //PACK国标码回写
        public delegate void ReceivedGBSNHandler(string gbsn);
        public event ReceivedGBSNHandler OnReceivedGBSN;

        //填充班次信息
        public delegate void ShiftChangedHandler(ClientShiftCfg csc);
        public event ShiftChangedHandler OnShiftChanged;
    }
}
